package educar.models;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import educar.db.DbConnection;
import educar.db.JPA;


public class poseeCargo {
	private static JPA jpa = new JPA();
	private Integer codigo;
	private String dni;
	
	public poseeCargo ( String dni,Integer codigo){
		this.setCodigo(codigo);
		this.setDni(dni);
	}
	
	
	public boolean save() {
		try {
			poseeCargo.getCargoByCargo(dni,Integer.toString(codigo));
			return false;
		} catch (datoNotFound e1) {
			String[] columns = {"dni","codigo"};

			PreparedStatement stm = jpa.newRecord("educar_dev.poseeCargo", columns);

			try {
				stm.setString(1, dni);
				stm.setString(2, Integer.toString(codigo));
				
			} catch (SQLException e) {
				e.printStackTrace();
				return false;
			}

			jpa.create(stm);
			return true;
		}
	}
	
	public static poseeCargo getCargoByCargo(String dni,String codigo) throws datoNotFound {
		ResultSet rs = null;
		ResultSet rs2 = null;
		poseeCargo p = null;

		rs = jpa.getByField("poseeCargo", "codigo", codigo);
		rs2=jpa.getByField("poseeCargo", "dni", dni);
		try {
			if (rs.next() && rs2.next()) {
				p = new poseeCargo( rs2.getString(2),Integer.parseInt(rs.getString(2)));
			} else {
				throw new datoNotFound();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return p;
	}

	public void destroy(String dni,String codigo) {
		String query= "DELETE from " + DbConnection.bd + ".poseeCargo"; 
    	query += " Where dni= '" + dni + "' and codigo= '"+codigo+"'";
		jpa.runUpdate(query);
	}

	
	public void setCodigo(Integer codigo){
		this.codigo=codigo;
	}
	
	public Integer getCodigo(){
		return this.codigo;
	}
	
	public void setDni(String dni){
		this.dni=dni;
	}
	
	public String getDni(){
		return this.dni;
	}
}

